<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormRules } from 'element-plus'
import jdfkService from '@/api/jdfk'
import wjfwSerivce from '@/api/wjfw'
import { Fj } from '@/api/jdfk-dto'
/*
 * 打开弹窗
 */
//
const emit = defineEmits(['refresh'])
const dialogVisible = ref(false)
const dialogType = ref('')
const currentRow = ref()
const openDialog = (row: any, type: string) => {
  dialogVisible.value = true
  dialogType.value = type
  currentRow.value = row
}

const dialogTitle = computed(() => (dialogType.value === 'zgfk' ? '整改反馈' : '申请复核'))
const qkLabel = computed(() => (dialogType.value === 'zgfk' ? '反馈情况' : '复核情况'))
/*
 * 确定按钮
 */
const form = ref({
  qk: '', // 情况
})

const rules = reactive<FormRules<any>>({
  qk: [{ required: true, message: '必填', trigger: 'change' }],
})

// 表单实例
const ruleFormRef = ref()
const loading = ref(false)
const confirm = () => {
  ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      let params
      loading.value = true
      if (dialogType.value === 'zgfk') {
        params = {
          fjList: yscFjList.value,
          fkqk: form.value.qk,
          jdbh: currentRow.value.jdbh,
        }
        jdfkService
          .savaFkjg(params)
          .then(() => {
            ElMessage.success('操作成功')
            dialogVisible.value = false
            emit('refresh')
          })
          .catch((err) => {
            !err.isError && ElMessage({ type: 'warning', message: err.message })
          })
          .finally(() => {
            loading.value = false
          })
      } else {
        params = {
          fjList: yscFjList.value,
          fhqksm: form.value.qk,
          jdbh: currentRow.value.jdbh,
        }
        jdfkService
          .saveSqfh(params)
          .then(() => {
            ElMessage.success('操作成功')
            dialogVisible.value = false
            emit('refresh')
          })
          .catch((err) => {
            !err.isError && ElMessage({ type: 'warning', message: err.message })
          })
          .finally(() => {
            loading.value = false
          })
      }
    }
  })
}

/*
 * 上传附件
 */
const dscFjList = ref<any[]>([])
const yscFjList = ref<Fj[]>([])
const uploadFj = (fj: any) => {
  const formData = new FormData()
  formData.append('file', fj.file)
  wjfwSerivce.upload(formData).then((res) => {
    let wjkzm = ''
    const lastDotIndex = fj.file.name.lastIndexOf('.')
    if (lastDotIndex !== -1 && lastDotIndex !== 0) {
      wjkzm = fj.file.name.slice(lastDotIndex + 1)
    }
    yscFjList.value.push({
      fjbh: res.wjbh,
      fjmc: fj.file.name,
      wjkzm,
    })
  })
}
// 限制上传相同的文件
const beforeUpload = (file: any) => {
  if (yscFjList.value.find((fj) => fj.fjmc === file.name)) {
    ElMessage.warning(`${file.name}已存在，请务重复上传`)
    return false
  }
  return true
}
// 删除上传成功的文件
const removeFj = (file: any) => {
  yscFjList.value = yscFjList.value.filter((fj) => fj.fjmc !== file.name)
}

const closeDialog = () => {
  dialogType.value = ''
  currentRow.value = undefined
  form.value = {
    qk: '',
  }
  ruleFormRef.value?.resetFields()
  dscFjList.value = []
  yscFjList.value = []
}
defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="600px"
    :close-on-click-modal="false"
    @close="closeDialog"
  >
    <el-form
      ref="ruleFormRef"
      :model="form"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item :label="qkLabel" prop="qk">
        <el-input v-model="form.qk" type="textarea" maxlength="200" :rows="4" />
      </el-form-item>
      <el-form-item label="附件" prop="fileList">
        <el-upload
          class="fj-upload"
          v-model:file-list="dscFjList"
          multiple
          :accept="'.pdf,.jpg,.jpeg,.png,.bmp'"
          :http-request="uploadFj"
          :on-remove="removeFj"
          :before-upload="beforeUpload"
        >
          <el-link type="primary" icon="Plus" :underline="false">上传</el-link>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirm" :loading="loading">确定</el-button>
        <el-button type="default" @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.fj-upload {
  width: 100%;
  :deep(.el-upload-list) {
    margin: 0;
    max-height: 100px;
    overflow-y: auto;
    .el-upload-list__item {
      margin: 0;
    }
  }
}
</style>
